﻿LootTrigger = AceLibrary("AceAddon-2.0"):new("AceConsole-2.0", "AceEvent-2.0")

function LootTrigger:OnInitialize()
    -- Called when the addon is loaded

		-- Slash Commands
		SlashCmdList["LOOTTRIGGER"] = LootTrigger_SlashHandler;
		SLASH_LOOTTRIGGER1 = "/lt";    		
	
	LootTrigger_Print("LootTrigger Version 0.1 loaded",1,0,0);
end;

function LootTrigger:OnEnable()
	-- Called when the addon is enabled
end;

function LootTrigger:OnDisable()
    -- Called when the addon is disabled
end;

-- Event Handler
function LootTrigger_SlashHandler(msg)
	local _, _, command, args = string.find(msg, "(%w+)%s?(.*)");
	if (command) then
		command = strlower(command);
	else
		PostUsage();
	end
	
	if(command == "post") then
		BuildLootMessage(args);
	elseif(command == "need") then
		BuildNeedMessage(args);
	elseif(command == "greed") then
		BuildGreedMessage(args);
	else
		PostUsage();
	end;
end;

function BuildLootMessage(args)
	if(args and args ~= "") then
		items = LootTrigger_GetItemInfo(args);
		if (#items >= 1) then
			PostLootMessage(items);
		else
			LootTrigger_Print("Keinen gültigen ItemLink gefunden!");
		end;
	else
		LootTrigger_Print("Keine Items angegeben!");
	end;
end;

function BuildNeedMessage(args)
	local _G = getfenv()
	_G["arg1"] = "need";
	_G["arg2"] = args;
	event = "CHAT_MSG_RAID";
	GetDKPAdmin_OnEvent(event);
end;

function BuildGreedMessage(args)
	local _G = getfenv()
	_G["arg1"] = "greed";
	_G["arg2"] = args;
	event = "CHAT_MSG_RAID";
	GetDKPAdmin_OnEvent(event);
end;

-- PostLootFunctions
function PostLootMessage(items)
	-- Post the AddonMSG for Loot
	local sName, sLink, iRarity, iLevel, iMinLevel, sType, sSubType, iStackCount, iEquipLoc, iTexture;
	SendAddonMessage("GDALootlist","start","RAID");
	for index,value in pairs(items) do
		LootTrigger_Print("XX:"..tostring(index).."XXX:"..tostring(value.id));
		sName, sLink, iRarity, iLevel, iMinLevel, sType, sSubType, iStackCount, iEquipLoc, iTexture = GetItemInfo(value.id);
		SendAddonMessage("GDALootlist",sLink..","..index..","..iTexture,"RAID");
	end;
	SendAddonMessage("GDALootlist","end","RAID");
end;

-- Item functions
function LootTrigger_GetItemInfo(args)
	local items = {}, itemName, itemLink;
	for idtoadd in string.gmatch(args, "item:(%d+):") do
		idtoadd = tonumber(idtoadd);
		itemName, itemLink = GetItemInfo(idtoadd);
		tinsert(items, {id=idtoadd, name=itemName});
		LootTrigger_Print("Added "..itemLink.."("..idtoadd..")".." to the Lootlist", 1, 1, 0);
	end
	return items;
end;

-- SupportFunctions
function LootTrigger_Print(msg, r, g, b)
	DEFAULT_CHAT_FRAME:AddMessage(msg, r, g, b);
end;

-- Post Usage
function PostUsage()
		LootTrigger_Print("USAGE:");
		LootTrigger_Print("/lt post [ITEMLINK(S)] - Übergibt die Lootliste an GetDKP");
end;